package com.ctg.behavior.calc.impala.transfer.userpath;

import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.ctg.behavior.calc.common.CtSQLConsts;
import com.ctg.behavior.calc.common.CtSQLParam;
import com.ctg.behavior.calc.impala.CtSQLTransfer;
import com.ctg.behavior.calc.impala.report.userpath.CtUserPathUserIdsReport;
import com.ctg.behavior.common.calc.CtCalc;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class CtUserPathTotalTransfer implements CtSQLTransfer {

	@Override
	public String doTransfer(CtCalc calcObject, CtSQLParam sqlParam) {
		if (!(calcObject instanceof CtUserPathUserIdsReport)) {
			log.warn("calcObject is not CtCalcTotal, class={}", calcObject.getClass());
			log.warn("calcObject: {}", JSON.toJSON(calcObject));
			log.warn("calcObject sqlParam: {}", JSON.toJSON(sqlParam));
			return "";
		}
		CtUserPathUserIdsReport report = (CtUserPathUserIdsReport) calcObject;
		// log.info("report={}", JSON.toJSONString(report));
		String theByProperty = report.getTheByProperty();

		StringBuilder impalaSQL = new StringBuilder();
		impalaSQL.append(" SELECT event AS event ");
		if (null != theByProperty) {
			impalaSQL.append(" , ").append(theByProperty);
			impalaSQL.append(" AS ").append(theByProperty);
		}
		impalaSQL.append(" , count(*) AS total FROM ( ");
		String userIdsSQL = sqlParam.getParam(CtSQLConsts.KEY_FILTER_SQL);
		impalaSQL.append(userIdsSQL);
		impalaSQL.append(" ) TT ");
		//where 
		impalaSQL.append(" WHERE TT.event is not null ");
		// group by
		impalaSQL.append(" GROUP BY TT.event ");
		if (null != theByProperty) {
			impalaSQL.append(" , TT.").append(theByProperty).append(" ");
		}

		String retSQL = impalaSQL.toString();
		log.info("retSQL={}", JSON.toJSONString(retSQL));

		return retSQL;
	}

}
